﻿using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ColorWanted.Plugin.GuidBuilder
{
    public partial class GuidBuilderForm : Form
    {
        private static readonly string[] FORMATS =
        {
            "N",
            "D",
            "B",
            "P",
            "X",
        };

        public GuidBuilderForm()
        {
            InitializeComponent();

            cbFormat.SelectedIndex = 0;
        }

        private void btnGen_Click(object sender, EventArgs e)
        {
            tbOutput.Clear();

            string fmt = FORMATS[cbFormat.SelectedIndex];

            var count = (int)numCount.Value;

            cbFormat.Enabled = false;
            numCount.Enabled = false;
            btnGen.Enabled = false;
            Generate(fmt, count);
        }

        private void Generate(string format, int count)
        {
            Task.Run(() =>
            {
                var buffer = new StringBuilder();
                try
                {
                    for (int i = 0; i < count; i++)
                    {
                        buffer.AppendLine(Guid.NewGuid().ToString(format));
                    }

                    tbOutput.Invoke(new MethodInvoker(() =>
                    {
                        tbOutput.AppendText(string.Join("", buffer));
                    }));
                }
                catch
                {
                    // ignore
                }
                finally
                {
                    buffer.Clear();

                    if (!IsDisposed)
                    {
                        Invoke(new MethodInvoker(() =>
                        {
                            cbFormat.Enabled = true;
                            numCount.Enabled = true;
                            btnGen.Enabled = true;
                        }));
                        Application.DoEvents();
                    }
                }
            });
        }
    }
}
